package t10086.Repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import t10086.Model.Entity.DeliveryRecord;


import java.util.List;

public interface DeliveryRecordRepository extends JpaRepository<DeliveryRecord, String> {
    @Query("SELECT dr FROM DeliveryRecord dr WHERE dr.orderNumber = :orderNumber")
    List<DeliveryRecord> findByOrderNumber(@Param("orderNumber") String orderNumber);


    @Query("SELECT dr FROM DeliveryRecord dr WHERE dr.serialNumber = :serialNumber")
    List<DeliveryRecord> findBySerialNumber(@Param("serialNumber") String serialNumber);
    @Query("SELECT dr FROM DeliveryRecord dr WHERE dr.serialNumber = :serialNumber and dr.orderNumber= :orderNumber")
    List<DeliveryRecord> findBySerialNumberAndOrderNumber(@Param("serialNumber")String serialNumber, @Param("orderNumber")String orderNumber);

    @Query("SELECT dr FROM DeliveryRecord dr WHERE dr.status = :status")
    List<DeliveryRecord> findByStatus(@Param("status") int status);

    @Modifying
    @Transactional
    @Query("UPDATE DeliveryRecord dr SET dr.status = :status ,dr.window= :window,dr.consumedTime=:consumedTime " +
            "WHERE dr.orderNumber = :orderNumber AND dr.serialNumber= :serialNumber")
    int updateDeliverRecordStatus(@Param("orderNumber") String orderNumber,@Param("serialNumber") String serialNumber,
                                  @Param("status") int status, @Param("window") int window, @Param("consumedTime") int consumedTime);

    @Modifying
    @Transactional
    @Query("UPDATE DeliveryRecord dr SET dr.status = 2 WHERE dr.status = 0 AND dr.serialNumber= :serialNumber")
    int deliverFailed(@Param("serialNumber") String serialNumber );
}
